// Original Author: Marc Belmont <code at marcbelmont.com>
// Contributors:


///////////////
// CONSTANTS //
///////////////

const CALCULATOR_HISTORY = "history";

//////////////////////////
// Class implementation //
//////////////////////////

function History(calc) {
  this.init(calc);
}

History.prototype = {
  list : null,
  index : 0,
  current_pos : 0,
  calculator : null,
  rdf : null,

  init : function(calc) {
    this.calculator = calc;
    this.list = document.getElementById(CALCULATOR_HISTORY);
    this.setInput();
    this.loadRDF();
  },

  loadRDF : function() {
    include("chrome://calculator/content/src/jslib/io/dirUtils.js");
    var du = new DirUtils();
    var path = du.getUserChromeDir();
    path += "\\" + CALCULATOR_NAME + ".rdf";
    include("chrome://calculator/content/src/jslib/io/file.js");
    include("chrome://calculator/content/src/jslib/rdf/rdf.js");
    include("chrome://calculator/content/src/jslib/rdf/rdfFile.js");
    include("chrome://calculator/content/src/jslib/rdf/rdfContainer.js");

    this.rdf = new RDFFile(path);
    this.readRDF();
  },

  buildRDF : function() {
    var seq = this.rdf.getRootSeq("urn:history");
    if (seq == null) {
      this.rdf.addRootSeq("urn:history");
    }
    var node = this.rdf.getNode("urn:history:list")
    if (node == null) {
      node = seq.addNode("list");
    }
    var list = new Array();
    for (var i = 0; i < this.list.getRowCount(); i++) {
      var item = this.list.getItemAtIndex(i);
      list[i] = new Object();
      list[i].name = "entry" + i;
      list[i].value = item.getAttribute('value');
    }
    node.setAllAttributes(list);
    this.rdf.flush();
  },

  readRDF : function() {
    var seq = this.rdf.getRootSeq("urn:history");
    if (seq == null) {
      this.rdf.addRootSeq("urn:history");
    }
    var node = this.rdf.getNode("urn:history:list")
    if (node == null) {
      node = seq.addNode("list");
    }
    var list = node.getAllAttributes();
    if (list != null) {
      for (var i = 0; i < list.length; i++) {
	if (i % 2 == 0)
	  this.addToList(list[i].value,"expression");
	else
	  this.addToList(list[i].value,"result");
      }
    }
    var h = this;
    setTimeout(function() {
      h.list.ensureIndexIsVisible(h.list.getRowCount() - 1);
    }, 0);
  },

  /////////////////////////
  // Setters and getters //
  /////////////////////////

  setValue : function(id, value) {
    try {
      document.getElementById(id).value = value;
    } catch (e) {
    }
  },

  getValue : function(id) {
    try {
      return document.getElementById(id).value;
    } catch (e) {
    }
    return null;
  },

  setInputByKey : function() {
    try {
      //       if (this.current_pos == 0) {
      // 	this.list.selectItem(this.list.getItemAtIndex(1));
      //       } else {
      // 	this.list.selectItem(this.list.getItemAtIndex(this.current_pos));
//       }
      //       alert(this.current_pos);
      //       alert(this.list.selectedItem);
      //      var item = this.list.getItemAtIndex(this.list.selectedItem);
      this.list.selectItem(this.list.getItemAtIndex(this.current_pos));
      var item = null
      if (this.current_pos == 0) {
	item = this.list.getItemAtIndex(0);
      } else {
	item = this.list.getItemAtIndex(this.current_pos);
      }
      this.list.scrollToIndex(this.current_pos - 1);
      // this.list.ensureIndexIsVisible(this.current_pos - 1);
      this.setValue(CALCULATOR_INPUT, item.getAttribute('value'));
      //      this.list.clearSelection();
    } catch (e) {
    }
  },
  scroll : function() {
    //     this.list.focus();
    //     this.list.clearSelection();
    this.list.scrollToIndex(0);
    //    this.list.scrollToIndex(this.list.getRowCount()-1);
  },

  clear : function() {
    try {
      var list = this.list;
      while (list.getRowCount() > 0) {
	list.removeItemAt(0);
      }
      this.current_pos = 0;
      this.index = 0;
      this.setInput();
      this.buildRDF();
    } catch (e) {
    }
  },

  //   keyHandler : function(e) {
  //     var keyChar = String.fromCharCode(e.which);
  //     alert(keyChar);
  //     if (keyChar == 'd') {
  //       alert("asd");
  //     }
  //   },

  ////////////////////////////////////////////////////////////////////////////////////////////
  // Commands
  ////////////////////////////////////////////////////////////////////////////////////////////

  previous : function() {
    try {
      this.current_pos--;
      if (this.current_pos < 0) {
	this.current_pos = 0;
      }
      this.setInputByKey();
    } catch (e) {
    }
  },

  next : function() {
    try {
      this.current_pos++;
      if (this.current_pos >= this.index) {
	this.current_pos = this.index - 1;
      }
      this.setInputByKey();
    } catch (e) {
    }
  },

  print : function() {
    var list = this.list;
    var w = window.open("", "Calculator",
			"height=600, width=400,scrollbars=yes,toolbar=1,location=1,status=1,menubar=1");

    var date = new Date();
    var str = "";
    if (list == null) {
      w.document.close();
    }
    for (var i = 0; i < list.getRowCount(); i++) {
      var item = list.getItemAtIndex(i);
      if (i % 2 == 0)
	str = str.concat("<br><div class='expression'>");
      else
	str = str.concat("<div class='result'>");
      str = str.concat(item.getAttribute('value'));
      str = str.concat("</div>");
    }
    w.document.body.innerHTML =
      ("<html><head><link type='text/css' rel='stylesheet' href='chrome://calculator/skin/print.css'></head><body>" +
       "<div class='comment'>Mozilla Calculator<br>" +
       date.toString() +
       "</div>" +
       str+
       "</body></html>");
    // w.document.close();
  },

  setInput : function() {
    try {
      var input = document.getElementById(CALCULATOR_INPUT);
      input.focus();
      this.list = document.getElementById(CALCULATOR_HISTORY);
      var list = this.list;
      var array = list.selectedItems;
      var listitem = array[0];
      if (!listitem.value) {
	return;
      }
      input.value = input.value + listitem.value;
      input = document.getElementById(CALCULATOR_INPUT);
    } catch (e) {
    }
  },

  addExpression : function(input, output) {
    this.addToList(input,"expression");
    this.addToList(output,"result");
    this.list.ensureIndexIsVisible(this.index - 1);
    this.buildRDF();
  },

  addToList : function(data, style) {
    try {
      this.list = document.getElementById(CALCULATOR_HISTORY);

      var newItem = document.createElement('listitem');
      newItem.setAttribute("value", data);
      newItem.setAttribute("class", style);

      var newCell = document.createElement('listcell');
      var newLabel = document.createElement('label');
      newLabel.setAttribute("value", data);
      newCell.appendChild(newLabel);

      var resultCell = document.createElement('listcell');
      var newButton = document.createElement('button');
      newButton.setAttribute("label", "Insert");
      resultCell.appendChild(newButton);

      newItem.appendChild(newCell);
      //      newItem.appendChild(resultCell);

      this.index++;
      this.current_pos = this.index;
      this.list.appendChild(newItem);
    } catch (e) {
    }
  }
}

////////////////////////////////////////////////////////////////////////////////////////////
// The end
////////////////////////////////////////////////////////////////////////////////////////////
